package com.bjsdzk.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * 胜顶智控平台管理
 *
 * @author YangTang
 * @time 2019/6/28.
 */
public class RongCloudUtils {

    private static final String APPKEY = "RC-App-Key";
    private static final String NONCE = "RC-Nonce";
    private static final String TIMESTAMP = "RC-Timestamp";
    private static final String SIGNATURE = "RC-Signature";

    private static final String UTF8 = "UTF-8";

    private static final String HOSTTYPE = "http://api.cn.ronghub.com";

    private static final String app_key = "ik1qhw09ive8p";
    private static final String app_secret = "wqFN3FpLtbx";


    public static String getToken(String userId, String name, String portraitUri) {
        String result = "";
        if (StringUtils.isBlank(portraitUri)) portraitUri = "http://image.bjsdzk.com/user.jpg";
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("&userId=").append(URLEncoder.encode(userId, UTF8));
            sb.append("&name=").append(URLEncoder.encode(name, UTF8));
            sb.append("&portraitUri=").append(URLEncoder.encode(portraitUri, UTF8));
            String body = sb.toString();
            if (body.indexOf("&") == 0) {
                body = body.substring(1);
            }
            HttpURLConnection conn = createPostHttpConnection(app_key, app_secret, "/user/getToken.json", "application/x-www-form-urlencoded");
            setBodyParameter(body, conn);
            result = returnResult(conn);
            JSONObject json = JSON.parseObject(result);
            if (json != null) {
                Integer code = json.getInteger("code");
                if (code == 200) {
                    result = json.getString("token");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static void setBodyParameter(String str, HttpURLConnection conn) throws IOException {
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(str.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }

    public static HttpURLConnection createPostHttpConnection(String appKey, String appSecret, String uri,
                                                             String contentType) throws IOException {
        String nonce = String.valueOf(Math.random() * 1000000);
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        StringBuilder toSign = new StringBuilder(appSecret).append(nonce).append(timestamp);
        String sign = hexSHA1(toSign.toString());
        uri = HOSTTYPE + uri;
        URL url = new URL(uri);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setInstanceFollowRedirects(true);
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);

        conn.setRequestProperty(APPKEY, appKey);
        conn.setRequestProperty(NONCE, nonce);
        conn.setRequestProperty(TIMESTAMP, timestamp);
        conn.setRequestProperty(SIGNATURE, sign);
        conn.setRequestProperty("Content-Type", contentType);

        return conn;
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }

    public static String returnResult(HttpURLConnection conn) throws Exception {
        InputStream input = null;
        if (conn.getResponseCode() == 200) {
            input = conn.getInputStream();
        } else {
            input = conn.getErrorStream();
        }
        String result = new String(readInputStream(input), StandardCharsets.UTF_8);
        return result;
    }

    public static String hexSHA1(String value) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(value.getBytes(StandardCharsets.UTF_8));
            byte[] digest = md.digest();
            return byteToHexString(digest);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static String byteToHexString(byte[] bytes) {
        return String.valueOf(Hex.encodeHex(bytes));
    }
}
